package com.example.remotecontrol.ui.scenes

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.remotecontrol.data.repository.SceneRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 场景管理界面的ViewModel
 */
@HiltViewModel
class ScenesViewModel @Inject constructor(
    private val sceneRepository: SceneRepository
) : ViewModel() {

    // 所有场景列表
    val scenes = sceneRepository.scenes.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyList()
    )
    
    // 收藏场景列表
    val favoriteScenes = sceneRepository.favoriteScenes.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyList()
    )
    
    // 场景执行状态
    private val _isExecutingScene = MutableStateFlow(false)
    val isExecutingScene: StateFlow<Boolean> = _isExecutingScene.asStateFlow()
    
    /**
     * 执行场景
     */
    suspend fun executeScene(sceneId: String): Boolean {
        if (_isExecutingScene.value) return false
        
        _isExecutingScene.value = true
        
        try {
            val result = sceneRepository.executeScene(sceneId)
            return result
        } finally {
            _isExecutingScene.value = false
        }
    }
    
    /**
     * 切换场景收藏状态
     */
    fun toggleFavorite(sceneId: String) {
        viewModelScope.launch {
            val scene = sceneRepository.getSceneById(sceneId) ?: return@launch
            sceneRepository.setSceneFavorite(sceneId, !scene.isFavorite)
        }
    }
    
    /**
     * 删除场景
     */
    fun deleteScene(sceneId: String) {
        viewModelScope.launch {
            sceneRepository.deleteScene(sceneId)
        }
    }
    
    /**
     * 创建示例场景数据（用于初始化演示）
     */
    fun createSampleScenes() {
        viewModelScope.launch {
            sceneRepository.createSampleScenes()
        }
    }
} 